package com.course.web.component.custom;

import com.course.web.biz.WebSpecBiz;
import com.course.web.component.base.BaseEdit;
import com.course.web.component.base.BaseGrid;
import com.course.web.component.base.EditGrid;
import com.course.web.model.SpecInfoVM;
import com.course.web.view.SpecWeekView;
import com.vaadin.data.Binder;
import com.vaadin.spring.annotation.SpringComponent;
import com.vaadin.spring.annotation.ViewScope;
import com.vaadin.ui.Button;
import com.vaadin.ui.FormLayout;
import com.vaadin.ui.Layout;
import com.vaadin.ui.TextField;

/**
 * Created by Justin on 2017/6/10.
 */
@SpringComponent
@ViewScope
public class SpecInfoGrid extends EditGrid<SpecInfoVM> {

    private final WebSpecBiz specBiz;

    public SpecInfoGrid(WebSpecBiz specBiz) {
        super(SpecInfoVM.class);
        this.specBiz = specBiz;
    }

    @Override
    protected void doInitMenu(Layout menu) {
        Button create = new Button("添加");
        menu.addComponent(create);
        create.addClickListener(event -> createShow());
    }

    @Override
    protected void doInitGrid(BaseGrid<SpecInfoVM> grid) {
        grid.addColumn(SpecInfoVM::getId, "ID");
        grid.addColumn(SpecInfoVM::getTitle, "标题");
        grid.addColumn(this::getState, "状态");
        grid.addButton(this::updateShow, "编辑");
        grid.addButton(this::plan, "排版");
        grid.addButton(this::delete, "删除");
    }

    @Override
    protected void doInitEdit(BaseEdit<SpecInfoVM> edit) {
        FormLayout form = new FormLayout();
        TextField title = new TextField("标题");
        form.addComponent(title);
        form.setMargin(false);
        Binder<SpecInfoVM> binder = edit.binder();
        binder.bind(title, "title");
        edit.initEdit(form);
    }

    @Override
    protected SpecInfoVM doCreate() {
        return new SpecInfoVM();
    }

    @Override
    protected SpecInfoVM doCreate(SpecInfoVM item) {
        return specBiz.createInfo(item);
    }

    @Override
    protected SpecInfoVM doUpdate(SpecInfoVM item) {
        return specBiz.updateInfo(item);
    }

    @Override
    protected SpecInfoVM doDelete(SpecInfoVM item) {
        return specBiz.deleteInfo(item);
    }

    private String getState(SpecInfoVM item) {
        return item.isLocked() ? "已发布" : "未发布";
    }

    private void plan(SpecInfoVM item) {
        getUI().getNavigator().navigateTo(SpecWeekView.NAME + "/" + item.getId());
    }

    public void enter() {
        init(specBiz.listInfo());
    }
}
